<?php

require_once('inc/users.php');
require_once('inc/functions.php');

define('SUBPAGE', 'login');

Users::startSession();

if (isset($_POST['openid_url']) || isset($_REQUEST['openid_mode'])) {
 // OpenID login attempt

 define('OPENID_SREG_REQUEST', 'nickname,email');
 require('poidsy/processor.php');

} else if (isset($_SESSION['openid']['error'])) {
 // OpenID error

 define('ERROR', $_SESSION['openid']['error']);
 unset($_SESSIONS['openid']);

} else if (isset($_SESSION['openid']) && $_SESSION['openid']['validated']) {
 // Successfull OpenID login attempt

 if (!Users::checkExists($_SESSION['openid']['identity'])) {
  $email = isset($_SESSION['openid']['sreg']['email']) ? $_SESSION['openid']['sreg']['email'] : 'openid@dmdirc.com';
  $display = isset($_SESSION['openid']['sreg']['nickname']) ? $_SESSION['openid']['sreg']['nickname'] : $_SESSION['openid']['identity'];
  Users::addUserOpenID($_SESSION['openid']['identity'], $email, $display);
 }
 
 if (Users::loginOpenID($_SESSION['openid']['identity'])) {
  unset($_SESSION['openid']);
  header('Location: /account');
  exit;
 } else {
  unset($_SESSION['openid']);
  define('ERROR', Users::getLastError());
 }

} else if (isset($_POST['user']) && isset($_POST['pass'])) {
 // Normal login attempt

 if (Users::login($_POST['user'], $_POST['pass'])) {
  header('Location: /account');
  exit;
 } else {
  define('ERROR', Users::getLastError());
 }
}

showHeader('Login');
?>
    <h2>Login</h2>
    <p>
     By logging in to the DMDirc addons site, you can rate addons and
     upload new ones.  Logging in is entirely optional for downloading
     addons.
    </p>
    <p>
     If you do not have a DMDirc addons account, you will need to
     <a href="/register">register</a> one.
    </p>
<?php

 if (defined('ERROR')) {
  echo '<div class="error"><p>' . htmlentities(ERROR) . '</p></div>';
 }

?>
    <form action="/login" method="post">
     <table>
      <tr><th>User name</th><td><input type="text" name="user"></td></tr>
      <tr><th>Password</th><td><input type="password" name="pass"></td></tr>
     </table>
     <input type="submit" value="Login">
    </form>

    <p>Alternatively, you can login using an OpenID identifier:</p>

    <form action="/login" method="post">
     <table>
      <tr><th>Identifier</th><td>
      <input type="text" name="openid_url" style="background: url('poidsy/openid.gif') no-repeat; padding-left: 20px;">
      </td></tr></table>
     <input type="submit" value="Login">
    </form>
<?php
	showFooter();
?>
